package com.sharp.portal.service;

import com.sharp.kernel.mybatis.repository.BaseMysqlRepository;
import com.sharp.kernel.utils.ReflectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.persistence.GeneratedValue;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Set;

/**
 * Title: PortalUploadService
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2020/11/13 15:51
 */
@Slf4j
@Service
public class PortalUploadService extends BasePortalUploadService {

    private static final String UPLOAD_KEY = "PORTAL_UPLOAD_PROGRESS";

    @Override
    public void uploadExcel(File file) {

    }

    @Override
    public String getUploadProgress() {
        return null;
    }

    @Override
    protected String buildProgressKey() {
        return UPLOAD_KEY;
    }

    @Override
    protected <ENTITY> boolean isDuplicate(ENTITY data, Set<Object> duplicateSet) {
        return false;
    }

    @Override
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected <ENTITY, SERVICE> int insert(List<ENTITY> dataList, SERVICE service) {
        Boolean generatedPrimaryKeyAutomatic = false;
        Boolean fullField = true;
        isGeneratedPrimaryKeyAutomatic(dataList.get(0), generatedPrimaryKeyAutomatic, fullField);
        if (generatedPrimaryKeyAutomatic) {
            if (fullField) {
                return ((BaseMysqlRepository) service).insertBatch(dataList);
            } else {
                return ((BaseMysqlRepository) service).insert(dataList);
            }
        } else {
            if (fullField) {
                return ((BaseMysqlRepository) service).insertBatchWithPrimaryKey(dataList);
            } else {
                return ((BaseMysqlRepository) service).insert(dataList);
            }
        }
    }

    private <ENTITY> void isGeneratedPrimaryKeyAutomatic(ENTITY entity, Boolean generatedPrimaryKeyAutomatic,
                                                         Boolean fullField) {
        Field[] fields = entity.getClass().getFields();
        for (Field field : fields) {
            if (field.getAnnotation(GeneratedValue.class) != null) {
                generatedPrimaryKeyAutomatic = true;
            }
            if (ReflectionUtil.getValue(entity, field) == null) {
                fullField = false;
            }
        }
    }


}
